import React, { useEffect, useState, useRef } from "react";
import HomeHead from "../components/HomeHead";
import avater from "@/assets/images/timg.jpg";
import { Swiper, Divider, DotLoading } from "antd-mobile";
import _ from "../assets/utils";
import "./Home.less";
import NewsItem from "../components/NewsItem";
import SkeletonAgain from "../components/SkeletonAgain";
// API
// import { queryNewsLatest } from "../api/api.js";
import api from "../api";
const Home = function Home() {
  //把时间转成这种8位的格式20191204
  const [today, setToday] = useState(_.formatTime(null, "{0}{1}{2}")),
    [bannerData, setBannerData] = useState([]),
    [newsList, setNewsList] = useState([]);
  const loadMore = useRef();
  // 轮播图的状态
  useEffect(() => {
    (async () => {
      try {
        // let { date, stories, top_stories } = await queryNewsLatest();
        let { date, stories, top_stories } = await api.queryNewsLatest();
        setToday(date);
        setBannerData(top_stories);
        newsList.push({
          date,
          stories,
        });
        setNewsList([...newsList]);
      } catch (_) {}
    })();
  }, []);
  // 加载更多  第一次渲染完毕，设置监听器，实现触底加载
  useEffect(()=>{
    let ob=new IntersectionObserver(async changes=>{
      let {isIntersecting}=changes[0];
      if(isIntersecting){
        // 加载更多的按钮出现在视口中【也就是触底了】
        try{
          let time=newsList[newsList.length-1]['date'];
          let res=await api.queryNewsBefore(time);
          newsList.push(res);
          setNewsList([...newsList]);
        }catch(_){}
      }
    })
    let loadMoreBox=loadMore.current
    ob.observe(loadMore.current)
    // 在组件销毁的时候，手动销毁监听器
    return ()=>{
      ob.unobserve(loadMoreBox);
      ob=null
    }
  },[])
  return (
    <div className="home-box">
      <HomeHead today={today}></HomeHead>
      {/* 轮播图 */}
      <div className="swiper-box">
        <Swiper loop autoplay allowTouchMove>
          {bannerData.map((swiper) => {
            return (
              <Swiper.Item key={swiper.id}>
                <img src={swiper.image} alt="" className="swiperImg" />
                <div className="desc">
                  <p className="title">{swiper.title}</p>
                  <p className="author">{swiper.hint}</p>
                </div>
              </Swiper.Item>
            );
          })}
        </Swiper>
      </div>
      {/* 每一天的新闻列表 */}
      <div>
        {newsList.length === 0 ? (
          <SkeletonAgain />
        ) : (
          newsList.map((list) => {
            return (
              <div className="news-box" key={list.date}>
                <Divider contentPosition="left">{list.date}</Divider>
                <div>
                  {list.stories.map((info) => {
                    return <NewsItem info={info} />;
                  })}
                </div>
              </div>
            );
          })
        )}
        {/* 加载更多 */}
        <div
          className="loadmore-box"
          ref={loadMore}
          style={{ display: newsList.length === 0 ? "none" : "block" }}
        >
          <DotLoading color="primary" />
          加载更多
        </div>
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />
      </div>
    </div>
  );
};

export default Home;
